package com.ruoyi.zsyh.controller;

import java.math.BigDecimal;
import java.util.*;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.utils.*;
import com.ruoyi.zsyh.domain.*;
import com.ruoyi.zsyh.service.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 服务订单Controller
 * 
 * @author yuexl
 * @date 2022-02-22
 */
@Controller
@RequestMapping("/zsyh/serviceOrder")
public class ZsyhServiceOrderController extends BaseController {
    private String prefix = "zsyh/serviceOrder";
    @Value("${wxconfig.appIdAppletUser}")
    private String appIdApplet;

    @Value("${wxconfig.appSecretAppletUser}")
    private String appSecretApplet;

    @Value("${wxconfig.partner}")
    private String partner;

    @Value("${wxconfig.partnerKey}")
    private String partnerKey;

    @Value("${wxconfig.notifyUrlFactoryRecharge}")
    private String notifyUrlFactoryRecharge;

    @Autowired
    private IZsyhServiceOrderService zsyhServiceOrderService;
    @Autowired
    private IZsyhServiceOrderApplymoneyService zsyhServiceOrderApplymoneyService;
    @Autowired
    private IZsyhServiceOrderPartsService zsyhServiceOrderPartsService;
    @Autowired
    private IZsyhAfterCommissionSettingService zsyhAfterCommissionSettingService;
    @Autowired
    private IZsyhServiceOrderCommissionService zsyhServiceOrderCommissionService;
    @Autowired
    private IZsyhAgentInfoService zsyhAgentInfoService;
    @Autowired
    private IZsyhServiceSettleService zsyhServiceSettleService;
    @Autowired
    private IZsyhUserRakerService zsyhUserRakerService;
    @Autowired
    private IZsyhUserRepairstoreService zsyhUserRepairstoreService;
    @Autowired
    private IZsyhPlatformUserService zsyhPlatformUserService;
    @Autowired
    private IZsyhAfterFactoryService zsyhAfterFactoryService;
    @Autowired
    private IZsyhAfterFactoryBalanceService zsyhAfterFactoryBalanceService;
    @Autowired
    private IZsyhServiceOrderLogService zsyhServiceOrderLogService;
    @Autowired
    private IZsyhServiceOrderSettleRepairService zsyhServiceOrderSettleRepairService;

    @RequiresPermissions("zsyh:serviceOrder:view")
    @GetMapping()
    public String serviceOrder() {
        return prefix + "/serviceOrder";
    }

    @RequiresPermissions("zsyh:serviceOrder:view")
    @GetMapping("/serviceOrderUnDeal")
    public String serviceOrderUnDeal() {
        return prefix + "/serviceOrderUnDeal";
    }

    /**
     * 查询服务订单列表
     */
    @RequiresPermissions("zsyh:serviceOrder:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(ZsyhServiceOrder zsyhServiceOrder) {
        startPage();
        List<ZsyhServiceOrder> list = zsyhServiceOrderService.selectZsyhServiceOrderList(zsyhServiceOrder);
        return getDataTable(list);
    }

    /**
     * 导出服务订单列表
     */
    @RequiresPermissions("zsyh:serviceOrder:export")
    @Log(title = "服务订单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(ZsyhServiceOrder zsyhServiceOrder) {
        List<ZsyhServiceOrder> list = zsyhServiceOrderService.selectZsyhServiceOrderList(zsyhServiceOrder);
        ExcelUtil<ZsyhServiceOrder> util = new ExcelUtil<ZsyhServiceOrder>(ZsyhServiceOrder.class);
        return util.exportExcel(list, "服务订单数据");
    }

    /**
     * 新增服务订单
     */
    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }

    /**
     * 新增保存服务订单
     */
    @RequiresPermissions("zsyh:serviceOrder:add")
    @Log(title = "服务订单", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(ZsyhServiceOrder zsyhServiceOrder) {
        //默认状态为未接单
        zsyhServiceOrder.setOrderState("0");
        return toAjax(zsyhServiceOrderService.insertZsyhServiceOrder(zsyhServiceOrder));
    }

    /**
     * 修改服务订单
     */
    @GetMapping("/edit/{id}/{type}")
    public String edit(@PathVariable("id") String id, @PathVariable("type") String type, ModelMap mmap) {
        ZsyhServiceOrder zsyhServiceOrder = zsyhServiceOrderService.selectZsyhServiceOrderById(id);
       /* //判断是否有配件单和费用单
        ZsyhServiceOrderParts zsyhServiceOrderParts = new ZsyhServiceOrderParts();
        zsyhServiceOrderParts.setOrderId(id);
        if(zsyhServiceOrderPartsService.selectZsyhServiceOrderPartsList(zsyhServiceOrderParts).size()>0){
            zsyhServiceOrder.setIsPartsOrder("是");
        }else{
            zsyhServiceOrder.setIsPartsOrder("否");
        }
        ZsyhServiceOrderApplymoney zsyhServiceOrderApplymoney = new ZsyhServiceOrderApplymoney();
        zsyhServiceOrderApplymoney.setOrderId(id);
        if(zsyhServiceOrderApplymoneyService.selectZsyhServiceOrderApplymoneyList(zsyhServiceOrderApplymoney).size()>0){
            zsyhServiceOrder.setIsApplyMoneyOrder("是");
        }else{
            zsyhServiceOrder.setIsApplyMoneyOrder("否");
        }*/
        mmap.put("zsyhServiceOrder", zsyhServiceOrder);
        if ("1".equals(type)) {
            return prefix + "/editPerson";
        } else {
            return prefix + "/edit";
        }
    }

    /**
     * 修改服务订单
     */
    @GetMapping("/review/{id}")
    public String review(@PathVariable("id") String id, ModelMap mmap) {
        ZsyhServiceOrder zsyhServiceOrder = zsyhServiceOrderService.selectZsyhServiceOrderById(id);
        mmap.put("zsyhServiceOrder", zsyhServiceOrder);
        return prefix + "/review";
    }

    /**
     * 结算服务订单
     */
    @GetMapping("/settle/{id}")
    public String settle(@PathVariable("id") String id, ModelMap mmap) {
        ZsyhServiceOrder zsyhServiceOrder = zsyhServiceOrderService.selectZsyhServiceOrderById(id);
        mmap.put("zsyhServiceOrder", zsyhServiceOrder);
        return prefix + "/settle";
    }

    /**
     * 修改服务订单
     */
    @GetMapping("/viewImage/{id}")
    public String viewImage(@PathVariable("id") String id, ModelMap mmap) {
        ZsyhServiceOrder zsyhServiceOrder = zsyhServiceOrderService.selectZsyhServiceOrderById(id);
        mmap.put("zsyhServiceOrder", zsyhServiceOrder);
        return prefix + "/viewImage";
    }

    /**
     * 取消服务订单
     */
    @GetMapping("/cancelOrder/{id}")
    public String cancelOrder(@PathVariable("id") String id, ModelMap mmap) {
        ZsyhServiceOrder zsyhServiceOrder = zsyhServiceOrderService.selectZsyhServiceOrderById(id);
        mmap.put("zsyhServiceOrder", zsyhServiceOrder);
        return prefix + "/cancelOrder";
    }

    /**
     * 修改保存服务订单
     */
    @RequiresPermissions("zsyh:serviceOrder:edit")
    @Log(title = "服务订单", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(ZsyhServiceOrder zsyhServiceOrder) {
        return toAjax(zsyhServiceOrderService.updateZsyhServiceOrder(zsyhServiceOrder));
    }

    /**
     * 删除服务订单
     */
    @RequiresPermissions("zsyh:serviceOrder:remove")
    @Log(title = "服务订单", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(zsyhServiceOrderService.deleteZsyhServiceOrderByIds(ids));
    }

    /**
     * 结算工单
     */
    @Transactional
    @RepeatSubmit
    @RequiresPermissions("zsyh:serviceOrder:remove")
    @Log(title = "结算工单", businessType = BusinessType.DELETE)
    @PostMapping("/settleServiceOrder")
    @ResponseBody
    public AjaxResult settleServiceOrder(String id) throws Exception {
        //获取订单提成金额
        ZsyhAfterCommissionSetting zsyhAfterCommissionSetting = zsyhAfterCommissionSettingService.selectZsyhAfterCommissionSettingById(1L);

        ZsyhServiceOrder zsyhServiceOrder = zsyhServiceOrderService.selectZsyhServiceOrderById(id);
        //进行微信转账
        BigDecimal settleMoney;
        Map<String, String> m = new HashMap<>();
        ZsyhUserRepairstore zsyhUserRepairstore = zsyhUserRepairstoreService.selectZsyhUserRepairstoreById(zsyhServiceOrder.getRepairStoreId());
        ZsyhPlatformUser zsyhPlatformUser = zsyhPlatformUserService.selectZsyhPlatformUserById(zsyhUserRepairstore.getUserId());
        m.put("openid",zsyhPlatformUser.getUserOpenid());
        m.put("orderId",id);
        m.put("money",zsyhServiceOrder.getOrderMoneyallRepair().toString());
//        m.put("money","0.3");//测试金额
        m.put("spbillCreateIp","127.0.0.1");
        Map<String, Object> responseMap = sendPayBZJ(m);
        if(responseMap != null && responseMap.size() > 0){
            if("SUCCESS".equals(responseMap.get("result_code").toString())){
                String paymentNo = responseMap.get("payment_no").toString();
                System.out.println("调用成功");
                //调用成功，修改工单状态，转账状态
                //修改工单状态为已支付
                zsyhServiceOrder.setOrderState("3");
                zsyhServiceOrder.setPaymentTime(new Date());
                zsyhServiceOrderService.updateZsyhServiceOrder(zsyhServiceOrder);
                //添加师傅结算信息
                ZsyhServiceOrderSettleRepair zsyhServiceOrderSettleRepair =new ZsyhServiceOrderSettleRepair();
                zsyhServiceOrderSettleRepair.setOrderId(zsyhServiceOrder.getId());
                zsyhServiceOrderSettleRepair.setRepairId(zsyhServiceOrder.getRepairStoreId());
                zsyhServiceOrderSettleRepair.setRepairOpenid(zsyhPlatformUser.getUserOpenid());
                zsyhServiceOrderSettleRepair.setSettleMoney(zsyhServiceOrder.getOrderMoneyallRepair());
                zsyhServiceOrderSettleRepair.setTransactionId(paymentNo);
                zsyhServiceOrderSettleRepair.setSettleName(ShiroUtils.getSysUser().getUserName());
                zsyhServiceOrderSettleRepairService.insertZsyhServiceOrderSettleRepair(zsyhServiceOrderSettleRepair);
                //大区分成，市县分成(分成详细和分成合计)
                //1.分成详细
                ZsyhServiceOrderCommission zsyhServiceOrderCommission = new ZsyhServiceOrderCommission();
                zsyhServiceOrderCommission.setId(IdWorker.getId());
                zsyhServiceOrderCommission.setOrderId(id);
                zsyhServiceOrderCommission.setRakerId(zsyhServiceOrder.getRakerId());
                zsyhServiceOrderCommission.setAgentId(zsyhServiceOrder.getAgentId());
                zsyhServiceOrderCommission.setAgentCommission(new BigDecimal(zsyhAfterCommissionSetting.getAgentCommission()).setScale(2,BigDecimal.ROUND_HALF_UP));
                zsyhServiceOrderCommission.setRakerCommission(new BigDecimal(zsyhAfterCommissionSetting.getRakerCommission()).setScale(2,BigDecimal.ROUND_HALF_UP));
                zsyhServiceOrderCommissionService.insertZsyhServiceOrderCommission(zsyhServiceOrderCommission);
                //2.分成合计
                String agentOpenId = "", rakerOpenId = "";
                String dateString = DateUtils.getDate();
                Integer year = Integer.valueOf(dateString.substring(0,4));
                Integer month = Integer.valueOf(dateString.substring(5,7));
                if(EmptyUtils.isNotEmpty(zsyhServiceOrder.getAgentId())){
                    ZsyhAgentInfo agentInfo = zsyhAgentInfoService.selectZsyhAgentInfoById(zsyhServiceOrder.getAgentId());
                    if(EmptyUtils.isNotEmpty(agentInfo)){
                        agentOpenId = agentInfo.getAgentOpenid();

                        ZsyhServiceSettle serviceSettle = new ZsyhServiceSettle();
                        serviceSettle.setAgentId(zsyhServiceOrder.getAgentId());
                        serviceSettle.setPeriodYear(year);
                        serviceSettle.setPeriodMonth(month);
                        List<ZsyhServiceSettle> list = zsyhServiceSettleService.selectZsyhServiceSettleList(serviceSettle);
                        if(list.size() == 0){
                            serviceSettle.setAgentOpenid(agentOpenId);
                            serviceSettle.setId(IdWorker.getId());
                            serviceSettle.setAgentSettleMoney(new BigDecimal(zsyhAfterCommissionSetting.getAgentCommission()).setScale(2,BigDecimal.ROUND_HALF_UP));
                            serviceSettle.setSettleStatue("1");
                            serviceSettle.setSettleType("1");
                            zsyhServiceSettleService.insertZsyhServiceSettle(serviceSettle);
                        }else{
                            ZsyhServiceSettle serviceSettle1 = list.get(0);
                            serviceSettle.setId(serviceSettle1.getId());
                            serviceSettle.setAgentSettleMoney((serviceSettle1.getAgentSettleMoney().add(new BigDecimal(zsyhAfterCommissionSetting.getAgentCommission()))).setScale(2, BigDecimal.ROUND_HALF_UP));
                            zsyhServiceSettleService.updateZsyhServiceSettle(serviceSettle);
                        }

                    }
                }
                if(EmptyUtils.isNotEmpty(zsyhServiceOrder.getRakerId())){
                    ZsyhUserRaker userRaker = zsyhUserRakerService.selectZsyhUserRakerById(zsyhServiceOrder.getRakerId());
                    if(EmptyUtils.isNotEmpty(userRaker)){
                        rakerOpenId = userRaker.getUserOpenid();
                        ZsyhServiceSettle serviceSettle = new ZsyhServiceSettle();
                        serviceSettle.setRakerId(zsyhServiceOrder.getRakerId());
                        serviceSettle.setPeriodYear(year);
                        serviceSettle.setPeriodMonth(month);
                        List<ZsyhServiceSettle> list = zsyhServiceSettleService.selectZsyhServiceSettleList(serviceSettle);
                        if(list.size() == 0){
                            serviceSettle.setRakerOpenid(rakerOpenId);
                            serviceSettle.setId(IdWorker.getId());
                            serviceSettle.setRakerSettleMoney(new BigDecimal(zsyhAfterCommissionSetting.getRakerCommission()).setScale(2,BigDecimal.ROUND_HALF_UP));
                            serviceSettle.setSettleStatue("1");
                            serviceSettle.setSettleType("2");
                            zsyhServiceSettleService.insertZsyhServiceSettle(serviceSettle);
                        }else{
                            ZsyhServiceSettle serviceSettle1 = list.get(0);
                            serviceSettle.setId(serviceSettle1.getId());
                            serviceSettle.setRakerSettleMoney((serviceSettle1.getRakerSettleMoney().add(new BigDecimal(zsyhAfterCommissionSetting.getRakerCommission()))).setScale(2, BigDecimal.ROUND_HALF_UP));
                            zsyhServiceSettleService.updateZsyhServiceSettle(serviceSettle);
                        }
                    }
                }
                //扣除厂家余额,修改冻结款
                ZsyhAfterFactory zsyhAfterFactory = zsyhAfterFactoryService.selectZsyhAfterFactoryById(zsyhServiceOrder.getFactoryId());
                if(zsyhAfterFactory.getFactoryBalance().compareTo(zsyhServiceOrder.getOrderMoneyallRepair()) != -1){
                    //余额充足
                    zsyhAfterFactory.setFactoryBalance(zsyhAfterFactory.getFactoryBalance().subtract(zsyhServiceOrder.getOrderMoneyallRepair()).setScale(2,BigDecimal.ROUND_HALF_UP));
                    zsyhAfterFactory.setFactoryFreeze(zsyhAfterFactory.getFactoryFreeze().subtract(zsyhServiceOrder.getOrderMoneyallRepair()).setScale(2,BigDecimal.ROUND_HALF_UP));
                    zsyhAfterFactoryService.updateZsyhAfterFactory(zsyhAfterFactory);
                    //解冻厂家冻结款
                    ZsyhAfterFactoryBalance zsyhAfterFactoryBalance = new ZsyhAfterFactoryBalance();
                    zsyhAfterFactoryBalance.setFactoryId(zsyhServiceOrder.getFactoryId());
                    zsyhAfterFactoryBalance.setBalanceMoney(zsyhServiceOrder.getOrderFrozenMoney());
                    zsyhAfterFactoryBalance.setBalanceClassify("2");
                    zsyhAfterFactoryBalance.setBalanceType("4");
                    zsyhAfterFactoryBalance.setBalanceMoneyAfter(zsyhAfterFactory.getFactoryBalance());
                    zsyhAfterFactoryBalance.setOrderId(zsyhServiceOrder.getId());
                    zsyhAfterFactoryBalance.setCreateName(ShiroUtils.getSysUser().getUserName());
                    zsyhAfterFactoryBalanceService.insertZsyhAfterFactoryBalance(zsyhAfterFactoryBalance);
                    //添加厂家余额变动记录
                    zsyhAfterFactoryBalance.setBalanceMoney(zsyhServiceOrder.getOrderMoneyallFactory());
                    zsyhAfterFactoryBalance.setBalanceType("3");
                    zsyhAfterFactoryBalance.setBalanceMoneyAfter(zsyhAfterFactory.getFactoryBalance().subtract(zsyhServiceOrder.getOrderMoneyallFactory()).setScale(2,BigDecimal.ROUND_HALF_UP));
                    zsyhAfterFactoryBalance.setCreateName(ShiroUtils.getSysUser().getUserName());
                    zsyhAfterFactoryBalanceService.insertZsyhAfterFactoryBalance(zsyhAfterFactoryBalance);
                    //添加工单追踪记录
                    ZsyhServiceOrderLog zsyhServiceOrderLog = new ZsyhServiceOrderLog();
                    zsyhServiceOrderLog.setOrderId(zsyhServiceOrder.getId());
                    zsyhServiceOrderLog.setLogType("3");
                    zsyhServiceOrderLog.setLogContent("平台转账成功");
                    zsyhServiceOrderLogService.insertZsyhServiceOrderLog(zsyhServiceOrderLog);
                    return AjaxResult.success("操作成功");
                }else{
                    return AjaxResult.error("厂家余额不足!");
                }
            }else{
                String err_code = responseMap.get("err_code").toString();
                String msg = "操作失败";
                switch (err_code){
                    case "AMOUNT_LIMIT":msg += ",金额超限!";break;
                    case "NOTENOUGH":msg += ",您的付款帐号余额不足或资金未到账!";break;
                    case "SYSTEMERROR":msg += ",系统繁忙，请稍后再试!";break;
                    case "V2_ACCOUNT_SIMPLE_BAN":msg += ",用户微信支付账户未知名，无法付款!";break;
                    case "SENDNUM_LIMIT":msg += ",该用户今日付款次数超过限制,如有需要请登录微信支付商户平台更改API安全配置!";break;
                    case "MONEY_LIMIT":msg += ",已经达到今日付款总额上限/已达到付款给此用户额度上限!";break;
                    case "FREQ_LIMIT":msg += ",超过频率限制，请稍后再试!";break;
                    default:break;
                }
                return AjaxResult.error(msg);
            }
        }

        return AjaxResult.success("操作成功");
    }

    /**
     * 订单分红转账
     * @param m
     * @return
     * @throws Exception
     */
    public Map<String, Object> sendPayBZJ(Map<String, String> m)throws Exception {

        String openId = m.get("openid");
        // 1 参数
        // 订单号
        String orderId = m.get("orderId");
        // 总金额以分为单位，不带小数点
        String totalFee = StringUtils.getMoney(m.get("money"));

        // 订单生成的机器 IP
        String spbill_create_ip = m.get("spbillCreateIp");

        // ---必须参数
        // 商户号
        String mch_id = partner;
        // 随机字符串
        String nonce_str = StringUtils.getNonceStr();

        String desc = "订单分红转账";

        SortedMap<String, String> packageParams = new TreeMap<String, String>();
        packageParams.put("mch_appid", appIdApplet);
        packageParams.put("mchid", mch_id);
        packageParams.put("nonce_str", nonce_str);
        packageParams.put("desc", desc);
        packageParams.put("partner_trade_no", orderId);
        // 这里写的金额为1 分到时修改
        packageParams.put("amount", totalFee);
        packageParams.put("spbill_create_ip", spbill_create_ip);
        packageParams.put("check_name", "NO_CHECK");
        packageParams.put("openid", openId);

        RequestHandler reqHandler = new RequestHandler(null, null);
        reqHandler.init(appIdApplet, appSecretApplet, partnerKey);

        String sign = reqHandler.createSign(packageParams);
        logger.info("第一次签名------------------------------" + sign);
        System.out.println("第一次签名------------------------------" + sign);
        String xml = "<xml>" + "<mch_appid>" + appIdApplet + "</mch_appid>" + "<mchid>"
                + mch_id + "</mchid>" + "<nonce_str>" + nonce_str
                + "</nonce_str>"
                + "<partner_trade_no>" + orderId + "</partner_trade_no>"
                + "<openid>" + openId + "</openid>"
                + "<check_name>NO_CHECK</check_name>"
                + "<amount>" + totalFee + "</amount>"
                + "<desc>"+ desc +"</desc>"
                + "<spbill_create_ip>" + spbill_create_ip + "</spbill_create_ip>"
                + "<sign>" + sign + "</sign>"
                + "</xml>";
        String createOrderURL = "https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers";


        Map<String, Object> map = new GetWxOrderno().sendPost(createOrderURL, xml);
        logger.info("info---------------------------------------------------------获取到的预支付ID：" + map);
        System.out.println("获取到的预支付ID：" + map);

        return map;
    }


}
